<script setup>
import ChatBox from '@/components/chat/ChatBox.vue'
import { inject, ref, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { useVisroleStore } from '@/stores/visrole'
import { useChannelStore } from '@/stores/channels'
import { useConfigStore } from '@/stores/config'
import { getStorageUrl, setDocumentText } from '@/utils/utils'
import chatApi from '@/apis/chat'

const route = useRoute()
const router = useRouter()

const authStore = useAuthStore()
const visroleStore = useVisroleStore()
const channelStore = useChannelStore()
const configStore = useConfigStore()

const drawerRef = inject('drawerRef')
const isSmallPage = inject('isSmallPage')

const visrole = ref({})
const visroleId = computed(() => parseInt(route.params?.id || 0))
const chatInfo = computed(() => ({
  title: visrole.value?.name,
  icon: visrole.value?.icon,
  favorite: visrole.value?.favorite,
}))

const role = computed(() => {
  return {
    user: { avatar: authStore.getAvatar() },
    assistant: { avatar: getStorageUrl(visrole.value?.icon || configStore.get('chat.avatar')) },
  }
})

const favorite = async () => {
  authStore.authOrLogin(
    async () => {
      await chatApi.role.favorite.toggle(visrole.value)
      visrole.value.favorite = !visrole.value.favorite
      ElMessage.success(visrole.value.favorite ? '已收藏' : '已取消')
    },
    { router, options: { confirm: true, redirect: route.fullPath } }
  )
}

const loadVisrole = async (id) => {
  visrole.value = (await chatApi.role.read(id, 'visrole')).data
  visroleStore.setActive(visrole.value)
  setDocumentText(visrole.value.name)
}

watch(visroleId, async (newId) => {
  if (newId > 0) {
    await loadVisrole(newId)
    if (isSmallPage.value) drawerRef.value.close()
  }
})

onMounted(async () => {
  await loadVisrole(visroleId.value)
  await channelStore.init()
})
</script>

<template>
  <div class="flex flex-col relative h-full w-full">
    <ChatBox
      show-favorite-btn
      show-clear-btn
      show-style-btn
      :default-display-style="visroleStore.displayStyle()"
      object-type="visrole"
      :object-id="visroleId"
      :channels="channelStore.data"
      :channel="channelStore.active"
      :role="role"
      :chat-info="chatInfo"
      :welcome-text="visrole?.config?.welcome"
      :example-text="visrole?.config?.sample"
      :prompt-placeholder="visrole?.config?.placeholder"
      @switch-channel="channelStore.switch"
      @switch-style="visroleStore.displayStyle"
      @favorite-chat="favorite"
    >
    </ChatBox>
  </div>
</template>

<style scoped></style>
